/*
 * Toedo
 * Copyright (C) 2009-2010 J. Devauchelle and contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 3 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

package org.toedo.controllers;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.ui.PlatformUI;

public class LogController {
	
	public static final String LOG_UPDATE = "LOG_UPDATE"; //$NON-NLS-1$
	
	private List<String> _log = null;
	private static LogController _instance = null;
	
	protected transient PropertyChangeSupport logChangeListeners;
	
	private LogController() {
		_log = new ArrayList<String>();
		logChangeListeners = new PropertyChangeSupport(this);
	}
	
	public static LogController getInstance() {
		if (_instance == null) {
			_instance = new LogController();
		}
		return _instance;
	}
	
	public void addToLog(String message) {
		_log.add(message);
		fireLogChange(LOG_UPDATE, null, message);
	}
	
	public int getNbLines() {
		return _log.size();
	}

	private String getMessages(List<String> log) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < log.size(); i++) {
			sb.append(log.get(i));
		}
		return sb.toString();
	}
	
	public String getMessages() {
		return getMessages(_log);
	}
	
	private void copyLogToClipboard(String textData) {
		Clipboard cb = new Clipboard(PlatformUI.getWorkbench().getDisplay());
		
		if (textData.length() > 0) {
			TextTransfer textTransfer = TextTransfer.getInstance();
			cb.setContents(new Object[]{textData}, new Transfer[]{textTransfer});
		}
	}
	
	public void copyLogToClipboard() {
		copyLogToClipboard(getMessages());
	}
	
	public void addLogChangeListener(PropertyChangeListener listener){
        if (listener == null) {
            throw new IllegalArgumentException();
        }
        this.logChangeListeners.addPropertyChangeListener(listener);
    }
	
	public void removeLogChangeListener(PropertyChangeListener listener){
        this.logChangeListeners.removePropertyChangeListener(listener);
    }
	
	protected void fireLogChange(String prop, Object old, Object newValue){
        if (this.logChangeListeners.hasListeners(prop)) {
            this.logChangeListeners.firePropertyChange(prop, old, newValue);
        }
    }

}
